import requests, json, pandas, duckdb, os
from config import ini_op
from time import strftime
from utils.path_utils import get_project_root
from database.duckdb.duckdb_base import get_connection



def run(header_cookie):
    timenow = str(strftime("%Y%m%d%H%M%S"))
    url_header, getListPage, body = ini_op.getinivalue('wldw_config', 'url_header', 'getListPage', 'body')
    url = url_header+getListPage
    header = header_cookie
    conn = get_connection()
    try:
        ksrq = conn.execute('select TIMESTAMP_LASTCHANGEDON from t_api_wldw order by TIMESTAMP_LASTCHANGEDON desc limit 1').fetchall()[0][0]
    except Exception:
        ksrq = '2010-01-01 00:00:00'
    print(ksrq)
    data = body.replace('#ksrq#', str(ksrq))

    result = requests.post(url, headers=header, json=json.loads(data), verify=False)
    #往来单位列表
    rows = json.loads(result.text)['Data']['Rows']
    print(len(rows))
    #将往来单位列表转化为DataFrame
    df = pandas.DataFrame(rows)

    #df数据注册为临时表
    conn.register("temp_wldw", df)
    #指定列创建新表
    conn.execute("""
        delete from t_api_wldw where id in (select id from temp_wldw) or code in (select code from temp_wldw);
        insert into t_api_wldw (
            id,
            code,
            name_chs,
            organizationcode,
            type,
            area,
            countryorregion,
            seclevel,
            seclevelid,
            state_asyncdeletestatus,
            state_isenabled,
            state_disabletime,
            timestamp_createdon,
            timestamp_lastchangedon,
            esun_api_update)
        select id,code,NAME$LANGUAGE$,ORGANIZATIONCODE,
                case when TYPE_NAME$LANGUAGE$ is null then '空' else TYPE_NAME$LANGUAGE$ end,
                AREA_NAME$LANGUAGE$,COUNTRYORREGION,SECLEVEL,SECLEVELID,STATE_ASYNCDELETESTATUS,STATE_ISENABLED,STATE_DISABLETIME,TIMESTAMP_CREATEDON,TIMESTAMP_LASTCHANGEDON,?
            from temp_wldw; 
        """, [timenow])
    conn.close()
